package fr.model.dao.Hib;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import fr.beans.User;

/**
 * @author Altenide-mov
 * DAO User.
 */
public class UserDaoHib extends HibernateDaoSupport implements IDaoUserHB {

	/**
	 * Log4J the logger.
	 */
	private static final Logger LOG = Logger
			.getLogger(UserDaoHib.class);	

	// properties


	/**
	 * The user.
	 */
	private User user;
	
	
	/**
	 * error opération base.
	 */
	private int error = 0;


	@Override
	public final int save(final User puser) {
		LOG.info("Enteringin save " + puser.getClass() + puser);

		// récupération de la session courante d'hibernate.
		final Session hibSession = getSessionFactory().getCurrentSession();

		// ouverture d'une transaction
		final Transaction transaction = hibSession.beginTransaction();

		try {
			hibSession.saveOrUpdate(puser);
			//envoi de la transaction
			transaction.commit();

		} catch (HibernateException e) {
			transaction.rollback();
			LOG.error("Save or update User error", e);
			error = 1;
		}

		return error;
	}

	@Override
	public final User readUser(final int pid) {
		
		try {
			getHibernateTemplate().get(User.class, pid);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public final List<User> showUsersList() {
		LOG.info("Entering in showUsersList");
		
		ArrayList<User> listUsers = null;
		try {
			listUsers = (ArrayList<User>) getHibernateTemplate().find("From User");
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		LOG.info("Exit showUsersList size is " + listUsers.size());
		return listUsers;
	}


	@Override
	public final boolean existUser(final User puser) {
		
		LOG.info("Entering in readUserByLogin(final User puser) :" + puser);
		
		boolean exist = !getHibernateTemplate().
				find("FROM User as u where u.login =?"
						, puser.getLogin()).isEmpty();
		
		
		LOG.debug(" User existing in base :" + exist);
		
		return exist;
	}







}
